/*
 * Copyright (C) 2010-2015 FBReader.ORG Limited <contact@fbreader.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */

package org.geometerplus.android.fbreader;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chineseall.reader.ui.ReadActivity;
import com.chineseall.reader.ui.util.GlobalApp;
import com.chineseall.reader.ui.widget.EPubZoomImageWidget;
import com.chineseall.singlebook.R;

import org.geometerplus.fbreader.bookmodel.FBHyperlinkType;
import org.geometerplus.fbreader.fbreader.FBReaderApp;
import org.geometerplus.zlibrary.text.view.ZLTextHyperlink;
import org.geometerplus.zlibrary.text.view.ZLTextHyperlinkRegionSoul;
import org.geometerplus.zlibrary.text.view.ZLTextImageRegionSoul;
import org.geometerplus.zlibrary.text.view.ZLTextRegion;
import org.geometerplus.zlibrary.text.view.ZLTextWordRegionSoul;

public class ProcessHyperlinkAction extends FBAndroidAction {

    class ReadCommentDialogContentView extends LinearLayout {

        private TextView mTxtCommentView;
        private LayoutInflater mLayoutInflater;
        private ImageView mImageView;

        public ReadCommentDialogContentView(Context context) {
            super(context);
            init();
        }

        public ReadCommentDialogContentView(Context context, AttributeSet attrs) {
            super(context, attrs);
            init();
        }

        public ReadCommentDialogContentView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            init();
        }

        private void init() {

            LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            setLayoutParams(lp);
            setOrientation(VERTICAL);
            mTxtCommentView = new TextView(getContext());
            int screenWidth = GlobalApp.getInstance().getScreenWidth();
            int screenHeight = GlobalApp.getInstance().getScreenHeight();

            mTxtCommentView.setMaxWidth(screenWidth - 80);
            mTxtCommentView.setPadding(15, 15, 15, 15);
            mTxtCommentView.setBackgroundResource(R.drawable.rv3_read_comment_dialog_bg_part_1);
            mTxtCommentView.setPadding(15, 15, 15, 15);
            mTxtCommentView.setTextSize(getContext().getResources().getDimensionPixelSize(R.dimen.rv440_read_comment_text_size));
            mTxtCommentView.setGravity(Gravity.LEFT | Gravity.TOP);
            mTxtCommentView.setTextColor(0xff383222);
            addView(mTxtCommentView, lp);
            lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            mTxtCommentView.setLayoutParams(lp);
            mImageView = new ImageView(getContext());
            mImageView.setImageResource(R.drawable.rv3_read_comment_arrow_down);
            lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            mImageView.setLayoutParams(lp);
            addView(mImageView, lp);
        }

        public int getPreHeight() {

            return mTxtCommentView.getMeasuredHeight() + mImageView.getMeasuredHeight();
        }

        public int getPreWidth() {
            return mTxtCommentView.getMeasuredWidth();
            //return Math.max(mTxtCommentView.getMeasuredWidth(), mImageView.getMeasuredWidth());
        }

        public void setText(String strContent) {
            mTxtCommentView.setText(strContent);
            mTxtCommentView.measure(0, 0);
            mImageView.measure(0, 0);
//

        }

        public void setAnchorPosition(boolean isUp, int anchorX) {
            mImageView.setImageResource(isUp ? R.drawable.rv3_read_comment_arrow_down : R.drawable.rv3_read_comment_arrow_up);
            LayoutParams lp = (LayoutParams) mImageView.getLayoutParams();
            lp.setMargins(anchorX - mImageView.getMeasuredWidth() / 2
                    , 0, 0, 0);
            removeView(mImageView);
            addView(mImageView, isUp ? 1 : 0);
        }


    }

    private EPubZoomImageWidget mZoomImageWidget;

    public ProcessHyperlinkAction(ReadActivity baseActivity, FBReaderApp fbreader) {
        super(baseActivity, fbreader);
    }

    @Override
    public boolean isEnabled() {
        return Reader.getTextView().getOutlinedRegion() != null;
    }

    @Override
    protected void run(Object ... params) {
        final ZLTextRegion region = Reader.getTextView().getOutlinedRegion();
        if (region == null) {
            return;
        }

        final ZLTextRegion.Soul soul = region.getSoul();
        if (soul instanceof ZLTextHyperlinkRegionSoul) {
            Reader.getTextView().hideOutline();
            Reader.getViewWidget().repaint();
            final ZLTextHyperlink hyperlink = ((ZLTextHyperlinkRegionSoul)soul).Hyperlink;
            switch (hyperlink.Type) {
                case FBHyperlinkType.EXTERNAL:
                    openInBrowser(hyperlink.Id);
                    break;
                case FBHyperlinkType.INTERNAL:
                //               case FBHyperlinkType.FOOTNOTE:
                {
//                    final AutoTextSnippet snippet = Reader.getFootnoteData(hyperlink.Id);
//                    if (snippet == null) {
//                        break;
//                    }
//
//                    Reader.Collection.markHyperlinkAsVisited(Reader.getCurrentBook(), hyperlink.Id);
//                    final boolean showToast;
//                    switch (Reader.MiscOptions.ShowFootnoteToast.getValue()) {
//                        default:
//                        case never:
//                            showToast = false;
//                            break;
//                        case footnotesOnly:
//                            showToast = hyperlink.Type == FBHyperlinkType.FOOTNOTE;
//                            break;
//                        case footnotesAndSuperscripts:
//                            showToast =
//                                    hyperlink.Type == FBHyperlinkType.FOOTNOTE ||
//                                            region.isVerticallyAligned();
//                            break;
//                        case allInternalLinks:
//                            showToast = true;
//                            break;
//                    }
//                    if (showToast) {
//                        final SuperActivityToast toast;
//                        if (snippet.IsEndOfText) {
//                            toast = new SuperActivityToast(BaseActivity, SuperToast.Type.STANDARD);
//                        } else {
//                            toast = new SuperActivityToast(BaseActivity, SuperToast.Type.BUTTON);
//                            toast.setButtonIcon(
//                                    android.R.drawable.ic_menu_more,
//                                    ZLResource.resource("toast").getResource("more").getValue()
//                            );
//                            toast.setOnClickWrapper(new OnClickWrapper("ftnt", new SuperToast.OnClickListener() {
//                                @Override
//                                public void onClick(View view, Parcelable token) {
//                                    Reader.getTextView().hideOutline();
//                                    Reader.tryOpenFootnote(hyperlink.Id);
//                                }
//                            }));
//                        }
//                        toast.setText(snippet.getText());
//                        toast.setDuration(Reader.MiscOptions.FootnoteToastDuration.getValue().Value);
//                        toast.setOnDismissWrapper(new OnDismissWrapper("ftnt", new SuperToast.OnDismissListener() {
//                            @Override
//                            public void onDismiss(View view) {
//                                Reader.getTextView().hideOutline();
//                                Reader.getViewWidget().repaint();
//                            }
//                        }));
//                        Reader.getTextView().outlineRegion(region);
//                        BaseActivity.showToast(toast);
//                    } else {
//                        Reader.tryOpenFootnote(hyperlink.Id);
//                    }
                    break;
                }
            }
        } else if (soul instanceof ZLTextImageRegionSoul) {
            Reader.getTextView().hideOutline();
            Reader.getViewWidget().repaint();
            final String url = ((ZLTextImageRegionSoul) soul).ImageElement.URI;
            final String alt = ((ZLTextImageRegionSoul) soul).ImageElement.alt;

            if (!TextUtils.isEmpty(alt)) {
                int screenWidth = GlobalApp.getInstance().getScreenWidth();
                int screenHeight = GlobalApp.getInstance().getScreenHeight();
                Dialog mCommentDialog = new Dialog(Reader.getAppContext(), R.style.dialog_nobackdim);
                ReadCommentDialogContentView contentView = new ReadCommentDialogContentView(Reader.getAppContext().getApplicationContext());
                mCommentDialog.setContentView(contentView);
                contentView.setText(alt);
                contentView.measure(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                int contentWidth = contentView.getPreWidth();


                boolean isUp = (region.getTop() >= 50 + contentView.getPreHeight());

                int centerX = region.getLeft() + (region.getRight() - region.getLeft()) / 2;
                int centerY = region.getTop() + (region.getBottom() - region.getTop()) / 2;

                FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) contentView.getLayoutParams();

//                  Toast.makeText(Reader.getAppContext(), "height:" + contentView.getPreHeight(), Toast.LENGTH_LONG).show();
//
//                LogUtil.e("LinkAction", "contentWidth:" + contentWidth + " :screenWidth" + screenWidth
//                                + " isUp:" + "height:" + contentView.getPreHeight()
//
//                );

                int leftX = centerX - contentWidth / 2;
                if (centerX - contentWidth / 2 < 40) {
                    leftX = 40;
                } else if (centerX + contentWidth / 2 > (screenWidth - 40)) {
                    leftX = screenWidth - 40 - contentWidth;
                }
                int anchorX = centerX - leftX;
                contentView.setAnchorPosition(isUp, anchorX);
                mCommentDialog.setCanceledOnTouchOutside(true);
                Window dialogWindow = mCommentDialog.getWindow();
                WindowManager.LayoutParams wlp = dialogWindow.getAttributes();
                dialogWindow.setGravity(Gravity.LEFT | Gravity.TOP);

                /*
                 * lp.x与lp.y表示相对于原始位置的偏移.
                 * 当参数值包含Gravity.LEFT时,对话框出现在左边,所以lp.x就表示相对左边的偏移,负值忽略.
                 * 当参数值包含Gravity.RIGHT时,对话框出现在右边,所以lp.x就表示相对右边的偏移,负值忽略.
                 * 当参数值包含Gravity.TOP时,对话框出现在上边,所以lp.y就表示相对上边的偏移,负值忽略.
                 * 当参数值包含Gravity.BOTTOM时,对话框出现在下边,所以lp.y就表示相对下边的偏移,负值忽略.
                 * 当参数值包含Gravity.CENTER_HORIZONTAL时
                 * ,对话框水平居中,所以lp.x就表示在水平居中的位置移动lp.x像素,正值向右移动,负值向左移动.
                 * 当参数值包含Gravity.CENTER_VERTICAL时
                 * ,对话框垂直居中,所以lp.y就表示在垂直居中的位置移动lp.y像素,正值向右移动,负值向左移动.
                 * gravity的默认值为Gravity.CENTER,即Gravity.CENTER_HORIZONTAL |
                 * Gravity.CENTER_VERTICAL.
                 *
                 * 本来setGravity的参数值为Gravity.LEFT | Gravity.TOP时对话框应出现在程序的左上角,但在
                 * 我手机上测试时发现距左边与上边都有一小段距离,而且垂直坐标把程序标题栏也计算在内了,
                 * Gravity.LEFT, Gravity.TOP, Gravity.BOTTOM与Gravity.RIGHT都是如此,据边界有一小段距离
                 */
                wlp.x = leftX; // 新位置X坐标
                wlp.y = isUp ? (region.getTop() - contentView.getPreHeight() - 20) : (
                        region.getBottom() + 20
                ); // 新位置Y坐标

                wlp.alpha = 1f; // 透明度

                // 当Window的Attributes改变时系统会w调用此函数,可以直接调用以应用上面对窗口参数的更改,也可以用setAttributes
                // dialog.onWindowAttributesChanged(lp);
                //dialogWindow.setAttributes(wlp);


                mCommentDialog.show();

                mCommentDialog = null;
                //ToastUtil.showToast(Reader.getAppContext(), ((ZLTextImageRegionSoul) soul).ImageElement.alt);
            } else if (false && url != null) {
                if(mZoomImageWidget == null){
                    mZoomImageWidget = new EPubZoomImageWidget(BaseActivity, url);
                }else{
                    mZoomImageWidget.setImageUrl(url);
                }
                mZoomImageWidget.show();
            }

        } else if (soul instanceof ZLTextWordRegionSoul) {
//            DictionaryUtil.openTextInDictionary(
//                    BaseActivity,
//                    ((ZLTextWordRegionSoul)soul).Word.getString(),
//                    true,
//                    region.getTop(),
//                    region.getBottom(),
//                    new Runnable() {
//                        public void run() {
//                            BaseActivity.outlineRegion(soul);
//                        }
//                    }
//            );
        }
    }

    private void openInBrowser(final String url) {

        FBReaderApp.Instance().getAppContext().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                final Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setAction("android.intent.action.VIEW");
                Uri content_url = Uri.parse(url);
                intent.setData(content_url);
                FBReaderApp.Instance().getAppContext().startActivity(intent);
            }
        });
    }
}
